import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:easy_chat_app/commons/utils/HttpUtils.dart';
import 'package:flutter/material.dart';

class UnknownUserHeadPortraitStoreTypeException implements Exception {}

class UserHeadPortrait {
  static Widget network(
      {required double size,
      required String userCode,
      required String userHeadPortrait,
      required String userHeadPortraitStoreType,
      double circularRadius = 5}) {
    if (userHeadPortraitStoreType == "local") {
      // headPortraitHash 用户解决头像更新后，页面图片不刷新的问题
      var headPortraitHash = md5.convert(utf8.encode(userHeadPortrait));
      String url =
          "${HttpUtils.baseURL}/app/user/getUserHeadPortrait?code=$userCode&headPortraitHash=$headPortraitHash";
      return NetworkUserHeadPortrait.create(
        size: size,
        url: url,
        circularRadius: circularRadius,
      );
    }
    if (userHeadPortraitStoreType == "http") {
      return NetworkUserHeadPortrait.create(
        size: size,
        url: userHeadPortrait,
        circularRadius: circularRadius,
      );
    }
    return defaultUserHeadPortrait(size: size);
  }

  static Widget defaultUserHeadPortrait({required double size}) {
    return FlutterLogo(
      size: size,
    );
  }

  static String buildUserHeadPortraitURL(
      {required String userCode,
      required String userHeadPortrait,
      required String userHeadPortraitStoreType}) {
    if (userHeadPortraitStoreType == "local") {
      // headPortraitHash 用户解决头像更新后，页面图片不刷新的问题
      var headPortraitHash = md5.convert(utf8.encode(userHeadPortrait));
      String url =
          "${HttpUtils.baseURL}/app/user/getUserHeadPortrait?code=$userCode&headPortraitHash=$headPortraitHash";
      return url;
    }
    if (userHeadPortraitStoreType == "http") {
      return userHeadPortrait;
    }
    throw Exception("头像存储类型未知");
  }
}

class NetworkUserHeadPortrait extends StatelessWidget {
  final double size;
  final String url;
  final double circularRadius;

  const NetworkUserHeadPortrait.create(
      {super.key,
      required this.size,
      required this.url,
      required this.circularRadius});

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: size,
      height: size,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(circularRadius),
        child: Image.network(url),
      ),
    );
  }
}
